import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:qilo/core/constants/app_icons.dart';
import '../../../core/providers/global_state_coordinator.dart';
import '../../../core/services/data_persistence_manager.dart';
import '../../../core/widgets/transgression_reporting_portal.dart';

class UserChatPage extends StatefulWidget {
  final String userId;

  const UserChatPage({super.key, required this.userId});

  @override
  State<UserChatPage> createState() => _ConversationInterfaceState();
}

class _ConversationInterfaceState extends State<UserChatPage> {
  final TextEditingController _textInputHandler = TextEditingController();
  final ScrollController _scrollNavigator = ScrollController();
  final List<DialogueEntry> _conversationHistory = [];
  late DataPersistenceManager _storageManager;

  @override
  void initState() {
    super.initState();
    _initializeConversationSpace();
  }

  void _initializeConversationSpace() async {
    _storageManager = DataPersistenceManager();
    await _storageManager.init();
    await _loadStoredMessages();
  }

  Future<void> _loadStoredMessages() async {
    final storageKey = 'chat_history_${widget.userId}';
    final storedData = _storageManager.getString(storageKey);

    if (storedData != null && storedData.isNotEmpty) {
      try {
        final List<dynamic> messageList = jsonDecode(storedData);
        setState(() {
          _conversationHistory.clear();
          _conversationHistory.addAll(
            messageList.map((item) => DialogueEntry.fromJson(item)).toList(),
          );
        });
      } catch (e) {
        debugPrint('Error loading chat history: $e');
      }
    }
  }

  /// 保存消息到本地存储
  Future<void> _saveMessageToStorage() async {
    final storageKey = 'chat_history_${widget.userId}';

    try {
      final messageList =
          _conversationHistory.map((msg) => msg.toJson()).toList();
      await _storageManager.setString(storageKey, jsonEncode(messageList));
    } catch (e) {
      debugPrint('Error saving chat history: $e');
    }
  }

  void _addMyMessage(String text) async {
    final newEntry = DialogueEntry(
      content: text,
      isFromCurrentUser: true,
      timestamp: DateTime.now(),
    );

    setState(() {
      _conversationHistory.add(newEntry);
    });

    // 保存到本地存储
    await _saveMessageToStorage();
    _scrollToBottom();
  }

  void _scrollToBottom() {
    Future.delayed(const Duration(milliseconds: 100), () {
      if (_scrollNavigator.hasClients) {
        _scrollNavigator.animateTo(
          _scrollNavigator.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  void _dispatchMessage() {
    if (_textInputHandler.text.trim().isNotEmpty) {
      _addMyMessage(_textInputHandler.text.trim());
      _textInputHandler.clear();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/my-bg.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: SafeArea(
          bottom: false,
          child: Column(
            children: [
              _buildAppBar(),
              Expanded(child: _buildChatAreaWithBackground()),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildAppBar() {
    return Consumer<GlobalStateCoordinator>(
      builder: (context, coordinator, child) {
        final targetUser = coordinator.getDefaultUserById(widget.userId);

        return Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
          child: Row(
            children: [
              GestureDetector(
                onTap: () => Navigator.of(context).pop(),
                child: Icon(
                  Icons.arrow_back_ios,
                  color: Colors.white,
                  size: 24.w,
                ),
              ),
              SizedBox(width: 16.w),

              // 用户头像
              Container(
                width: 40.w,
                height: 40.w,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: targetUser == null ? Colors.white : null,
                  image:
                      targetUser?.avatar.isNotEmpty == true
                          ? DecorationImage(
                            image: AssetImage(targetUser!.avatar),
                            fit: BoxFit.cover,
                          )
                          : null,
                ),
                child:
                    targetUser == null
                        ? Icon(
                          MyIcons.iconPeople,
                          size: 24.w,
                          color: Colors.grey[600],
                        )
                        : null,
              ),

              SizedBox(width: 12.w),

              Expanded(
                child: Text(
                  targetUser?.userName ?? 'Unknown User',
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: FontWeight.w600,
                    color: Colors.white,
                    fontFamily: 'Poppins',
                  ),
                ),
              ),

              GestureDetector(
                onTap: _handleChatReport,
                child: Icon(
                  MyIcons.iconReport,
                  color: Colors.white,
                  size: 24.w,
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildChatAreaWithBackground() {
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/activity-bg.png'),
          fit: BoxFit.fill,
        ),
      ),
      child: Column(
        children: [
          Expanded(child: _buildConversationDisplay()),
          _buildTextInputArea(),
        ],
      ),
    );
  }

  Widget _buildConversationDisplay() {
    return ListView.builder(
      controller: _scrollNavigator,
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      itemCount: _conversationHistory.length,
      itemBuilder: (context, index) {
        return _buildDialogueBubble(_conversationHistory[index]);
      },
    );
  }

  Widget _buildDialogueBubble(DialogueEntry dialogueEntry) {
    return Consumer<GlobalStateCoordinator>(
      builder: (context, coordinator, child) {
        final currentUser = coordinator.currentUser;
        final targetUser = coordinator.getDefaultUserById(widget.userId);

        return Container(
          margin: EdgeInsets.only(bottom: 16.h),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment:
                dialogueEntry.isFromCurrentUser
                    ? MainAxisAlignment.end
                    : MainAxisAlignment.start,
            children: [
              if (!dialogueEntry.isFromCurrentUser) ...[
                CircleAvatar(
                  radius: 20.r,
                  backgroundImage:
                      targetUser?.avatar.isNotEmpty == true
                          ? AssetImage(targetUser!.avatar)
                          : const AssetImage('assets/images/user_avatar.png'),
                  backgroundColor: Colors.grey[300],
                ),
                SizedBox(width: 12.w),
              ],
              Flexible(
                child: Container(
                  constraints: BoxConstraints(
                    maxWidth: MediaQuery.of(context).size.width * 0.7,
                  ),
                  padding: EdgeInsets.all(16.w),
                  decoration: BoxDecoration(
                    color:
                        dialogueEntry.isFromCurrentUser
                            ? const Color(0xFFCD8B76)
                            : const Color(0xFFD4A574).withValues(alpha: 0.8),
                    borderRadius: BorderRadius.circular(16.r),
                  ),
                  child: Text(
                    dialogueEntry.content,
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.white,
                      fontFamily: 'Poppins',
                      height: 1.4,
                    ),
                  ),
                ),
              ),
              if (dialogueEntry.isFromCurrentUser) ...[
                SizedBox(width: 12.w),
                CircleAvatar(
                  radius: 20.r,
                  backgroundImage:
                      currentUser?.avatar.isNotEmpty == true
                          ? AssetImage(currentUser!.avatar)
                          : const AssetImage('assets/images/user_avatar.png'),
                  backgroundColor: Colors.grey[300],
                ),
              ],
            ],
          ),
        );
      },
    );
  }

  Widget _buildTextInputArea() {
    return Consumer<GlobalStateCoordinator>(
      builder: (context, coordinator, child) {
        final currentUser = coordinator.currentUser;

        return Container(
          padding: EdgeInsets.all(16.w),
          child: Row(
            children: [
              CircleAvatar(
                radius: 24.r,
                backgroundImage:
                    currentUser?.avatar.isNotEmpty == true
                        ? AssetImage(currentUser!.avatar)
                        : const AssetImage('assets/images/user_avatar.png'),
                backgroundColor: Colors.grey[300],
              ),

              SizedBox(width: 12.w),

              // 输入框容器
              Expanded(
                child: Container(
                  height: 60.h,
                  decoration: BoxDecoration(
                    color: const Color(0xFFD4A574).withValues(alpha: 0.8),
                    borderRadius: BorderRadius.circular(30.r),
                  ),
                  child: Row(
                    children: [
                      // 输入框区域
                      Expanded(
                        child: Container(
                          padding: EdgeInsets.symmetric(horizontal: 20.w),
                          child: TextField(
                            controller: _textInputHandler,
                            style: TextStyle(
                              fontSize: 16.sp,
                              color: Colors.white,
                              fontFamily: 'Poppins',
                            ),
                            decoration: InputDecoration(
                              hintText: 'Say Something',
                              hintStyle: TextStyle(
                                fontSize: 16.sp,
                                color: Colors.white.withValues(alpha: 0.7),
                                fontFamily: 'Poppins',
                              ),
                              border: InputBorder.none,
                              contentPadding: EdgeInsets.zero,
                            ),
                            onSubmitted: (_) => _dispatchMessage(),
                          ),
                        ),
                      ),

                      // 右侧发送按钮
                      Padding(
                        padding: EdgeInsets.all(6.w),
                        child: GestureDetector(
                          onTap: _dispatchMessage,
                          child: Container(
                            width: 48.w,
                            height: 48.w,
                            decoration: const BoxDecoration(
                              color: Color(0xFFCD8B76),
                              shape: BoxShape.circle,
                            ),
                            child: Icon(
                              MyIcons.iconSend,
                              color: Colors.white,
                              size: 18.w,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 处理聊天举报
  void _handleChatReport() {
    TransgressionReportingPortal.manifestReportingRealm(
      context,
      targetId: widget.userId,
      targetType: 'chat_conversation',
      onReportSubmitted: (transgression) {
        // 举报成功后删除所有消息并返回上一页
        _deleteAllMessagesAndGoBack();
      },
    );
  }

  /// 删除所有消息并返回上一页
  void _deleteAllMessagesAndGoBack() async {
    // 清空内存中的消息记录
    setState(() {
      _conversationHistory.clear();
    });

    // 删除存储中的消息记录
    final storageKey = 'chat_history_${widget.userId}';
    await _storageManager.remove(storageKey);

    // 返回上一页
    if (mounted) {
      Navigator.of(context).pop();
    }
  }

  @override
  void dispose() {
    _textInputHandler.dispose();
    _scrollNavigator.dispose();
    super.dispose();
  }
}

class DialogueEntry {
  final String content;
  final bool isFromCurrentUser;
  final DateTime timestamp;

  DialogueEntry({
    required this.content,
    required this.isFromCurrentUser,
    required this.timestamp,
  });

  /// 从JSON创建DialogueEntry
  factory DialogueEntry.fromJson(Map<String, dynamic> json) {
    return DialogueEntry(
      content: json['content'] ?? '',
      isFromCurrentUser: json['isFromCurrentUser'] ?? false,
      timestamp: DateTime.parse(
        json['timestamp'] ?? DateTime.now().toIso8601String(),
      ),
    );
  }

  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'content': content,
      'isFromCurrentUser': isFromCurrentUser,
      'timestamp': timestamp.toIso8601String(),
    };
  }
}
